﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Authorization
{
    /// <summary>
    /// BootstrapAdmin 应用程序授权要求类
    /// </summary>
    internal class BootstrapAdminAppRequirement : AuthorizationHandler<BootstrapAdminAppRequirement>, IAuthorizationRequirement
    {
        /// <summary>
        /// 处理授权要求方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, BootstrapAdminAppRequirement requirement)
        {
            if (context.User.Identity.IsAuthenticated)
            {
                BootstrapAdminAuthenticationExtensions.AddRoles(context.User, BootstrapAdminAuthenticationExtensions.RetrieveRolesByUserName(context.User.Identity.Name), new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme));

                // 判断应用程序授权
                var appId = BootstrapAdminAuthenticationExtensions.AppId;
                if (string.IsNullOrEmpty(appId)) context.Succeed(this);
                else if (context.User.IsInRole("Administrators")) context.Succeed(this);
                else if (BootstrapAdminAuthenticationExtensions.RetrieveAppsByUserName(context.User.Identity.Name).Any(a => a == appId)) context.Succeed(this);
            }
            return Task.CompletedTask;
        }
    }
}
